#!/usr/bin/php
<?php

const PACKET_MAX = 8192;

function recv($cli)
{
    $data = socket_read($cli, PACKET_MAX);
    $len = ord($data[1]) & 127;

    $mask = substr($data, 2, 4);
    $data = substr($data, 6);

    $str = "";
    for ($i = 0; $i < $len; $i++) {
        $str .= $data[$i] ^ $mask[$i % 4];
    }

    return $str;
}

function main($argc, & $argv)
{
/*
 *     $web = file_get_contents('/dev/shm/websocket.tmp');
 *     $http = explode("\r\n", $web);
 *     $key = explode(': ', $http[9]);
 *     $orgin = explode(': ', $http[7])[1];
 *     // print_r($http);
 *     printf("#%s#", $key[1]);
 *     // echo 'X'.$orgin.'X', PHP_EOL;
 * 
 *     exit(0);
 */


    $sd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!$sd) {
        echo socket_strerror(socket_last_error($sd)), PHP_EOL;
        return 0;
    }

    socket_set_option($sd, SOL_SOCKET, SO_REUSEPORT, 1);

    if (!socket_bind($sd, "3.3.3.9", 9999)) {
        echo socket_strerror(socket_last_error($sd)), PHP_EOL;
        goto ERR1;
    }

    if (!socket_listen($sd, 5)) {
        echo socket_strerror(socket_last_error($sd)), PHP_EOL;
        goto ERR1;
    }

    $cli = socket_accept($sd);
    $packet = socket_read($cli, 1024);
    socket_getpeername($cli, $ip, $port);
    // echo $ip, "[", $port, "]: ", $packet, PHP_EOL;
    preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $packet, $key);
    $reply = "HTTP/1.1 101 Switching Protocol\r\n";
    $reply .= "Upgrade: WebSocket\r\n";
    $reply .= "Connection: Upgrade\r\n";
    $reply .= "Sec-WebSocket-Accept: ".base64_encode(sha1($key[1].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true))."\r\n\r\n";
    socket_write($cli, $reply);

    echo "recv: ", recv($cli), PHP_EOL;

    socket_close($cli);
    socket_close($sd);
    return 0;

ERR1:
    socket_close($cli);

    return 0;
}

exit(main($argc, $argv));

